<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="广告账户*" prop="advertiserId">
              <AdvertiserSelect ref="accountList" @update:modelValue="getAdvertiserId" />
            </el-form-item>
            <el-form-item label="资产ID" prop="platformId">
              <el-input v-model="queryParams.platformId" placeholder="请输入资产ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="资产名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入资产名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Refresh" v-hasPermi="['oce:productStore:syncProductStore']">同步商品库 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:productStore:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oce:productStore:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:productStore:export']">导出 </el-button>
          </el-col>
          <div class="flex items-center text-[12px] tips">
            <div class="ml-[10px] label">当前操作帐户：</div>
            <div class="val" :class="appStore.accountName ? 'text-[#409EFF]' : 'text-[#f00]'">
              {{ appStore.accountName || '未设置' }}
            </div>
          </div>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-row>
        <el-col :span="5">
          <!-- <el-card class="grid-content" shadow="never"> -->
          <!-- <div class="grid-content"> -->
          <!-- <el-card shadow="never"> 资产列表 </el-card>
              <el-table v-loading="loading" :data="productStoreList">
                <el-table-column label="商品库名称" align="left" prop="assetName">
                  <template #default="scope">
                    <div @click="handleClick(scope.row)">{{ scope.row.assetName }}</div>
                  </template>
                </el-table-column>
              </el-table> -->
          <div class="vertical-list-container">
            <div class="list-title">资产列表</div>
            <div
              class="list-item"
              v-for="(item, index) in productStoreList"
              :key="index"
              @click="handleClick(item, index)"
              :class="{ 'active': selectAssetNameId === index }"
            >
              {{ item.assetName }}
            </div>
            <div class="list-btn">
              <el-button plain type="primary" icon="Plus" @click="handleAdd">添加资产</el-button>
            </div>
          </div>
          <!-- </div> -->
          <!-- </el-card> -->
        </el-col>
        <el-col :span="19" style="padding: 0px 20px">
          <el-card class="grid-content bg-purple-light" style="margin-bottom: 20px">
            <div class="flex space-x-4">
              <div class="flex-1">
                <div class="flex items-center">
                  <div class="label">{{ selectAssetItem?.assetName }}</div>
                </div>
                <div class="flex items-center assets-title-text">
                  <div class="text">小程序AppID:{{ selectAssetItem?.microAppId }}</div>
                  <div class="text">小程序资产ID:{{ selectAssetItem?.assetId }}</div>
                </div>
              </div>
              <div class="btn-group">
                <el-button type="primary" plain icon="Edit" @click="handleAddEvent">新增事件</el-button>
              </div>
            </div>
          </el-card>
          <el-card>
            <div class="grid-content bg-purple-light">
              <el-table v-loading="loading" :data="eventConfigsList">
                <el-table-column label="事件名称" align="center" prop="eventCnName" />
                <el-table-column label="优化目标" align="center" prop="eventCnName" />
                <el-table-column label="事件回传方式" align="center" prop="trackTypes">
                  <template #default="scope">
                    <div>
                      {{ scope.row.trackTypes == 'MINI_PROGRAME_API' ? 'API回传' : '未知' }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!--      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>-->
    </el-card>
    <!-- 新增事件 -->
    <el-dialog :title="dialog.eventTitle" v-model="dialog.eventVisible" width="600px" append-to-body>
      <el-form ref="productEventFormRef" :model="eventForm" :rules="rulesEvent" label-width="110px">
        <el-form-item label="事件名称" prop="eventId">
          <el-select v-model="eventForm.eventId" placeholder="请选择资产类型" clearable @change="changeEvent">
            <el-option v-for="(itm, idx) in eventList" :key="idx" :label="itm.eventCnName" :value="itm.eventId" />
          </el-select>
        </el-form-item>
        <el-form-item label="事件说明" prop="miniProgramAsset">
          <el-input v-model="eventsListItem.description" placeholder="请输入事件说明" clearable disabled type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitEventForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增资产 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="productStoreFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="选择资产类型" prop="assetType">
          <el-select v-model="form.assetType" placeholder="请选择资产类型" clearable disabled>
            <el-option v-for="dict in platformIdOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择小程序" prop="miniProgramAsset">
          <el-select v-model="form.miniProgramAsset.instanceId" placeholder="选择小程序" clearable @change="miniProgramChange">
            <el-option v-for="(itm, idx) in miniProgramsList" :key="idx" :label="itm.name" :value="itm.instanceId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductStore" lang="ts">
import {
  getEventAllAssetsList,
  getEventManagerConfigs,
  getMicroMicroAppList,
  getQueryToolsMicroAppNew,
  addCreateEventManagerAssets,
  addCreateEventManagerEvents,
  getEventManagerAvailableEventsList
} from '@/api/advertisement/eventAssets';
import {
  EventAssetsVo,
  EventAssetsQuery,
  EventManagerConfigsVo,
  EventManagerConfigsQuery,
  ProductStoreForm,
  PageData,
  DialogOption
} from '@/api/advertisement/eventAssets/types';

import { useAppStore } from '@/store/modules/app';

const appStore = useAppStore();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productStoreList = ref<EventAssetsVo[]>([]);
const eventConfigsList = ref<EventManagerConfigsVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const eventsListItem = ref({
  description: ''
});
const selectAssetNameId = ref(0);
const selectAssetItem = ref();
const miniProgramsList = ref([]);
const queryFormRef = ref<ElFormInstance>();
const productStoreFormRef = ref<ElFormInstance>();
const productEventFormRef = ref<ElFormInstance>();
const platformIdOptions = ref([{ dictLabel: '抖音小程序', dictValue: 'MINI_PROGRAME' }]);
const dialog = reactive<DialogOption>({
  eventVisible: false,
  eventTitle: '新增事件',
  visible: false,
  title: ''
});
const newAdvertiserId = ref();
const eventList = ref([]);
const initFormData: ProductStoreForm = {
  platformId: undefined,
  accountId: appStore.accountId,
  advertiserId: undefined,
  name: undefined,
  productIndustry: undefined,
  assetType: undefined,
  miniProgramAsset: {
    instanceId: undefined,
    miniProgramName: undefined,
    miniProgramType: undefined,
    miniProgramId: undefined
  }
};
const initEventFormData: ProductStoreForm = {
  platformId: undefined,
  accountId: appStore.accountId,
  advertiserId: undefined,
  assetId: undefined,
  eventId: undefined,
  trackTypes: undefined
};
const data = reactive<PageData<ProductStoreForm, EventAssetsQuery>>({
  form: { ...initFormData },
  eventForm: { ...initEventFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    accountId: appStore.accountId,
    // advertiserId: 1820572205006868, // 测试
    advertiserId: undefined,
    assetId: undefined,
    assetName: undefined,
    params: {}
  },
  rules: {
    miniProgramAsset: [{ required: true, message: '小程序不能为空', trigger: 'blur' }],
    accountId: [{ required: true, message: '管家账号id不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '商品库名称不能为空', trigger: 'blur' }]
  },
  rulesEvent: {
    miniProgramAsset: [{ required: true, message: '小程序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, eventForm, form, rules } = toRefs(data);
//
const changeEvent = (val) => {
  eventList.value.forEach((item) => {
    if (item.eventId == val) {
      eventsListItem.value = item;
    }
  });
};
// 创建事件
const handleAddEvent = async () => {
  dialog.eventTitle = '创建事件';
  dialog.eventVisible = true;
};
const handleAvailableEventsList = async () => {
  getEventManagerAvailableEventsList(queryParams.value).then((res) => {
    eventList.value = res.data;
    changeEvent(res.data[0].eventId);
  });
};
// 添加事件
const submitEventForm = () => {
  // proxy.$refs.productEventFormRef.validate((valid) => {
  // if (valid) {
  if (eventForm.value.eventId == undefined) {
    proxy.$modal.msgError('请选择事件');
    return;
  }
  buttonLoading.value = true;
  eventForm.value.accountId = appStore.accountId;
  eventForm.value.advertiserId = newAdvertiserId.value;
  // eventForm.value.advertiserId = queryParams.value.advertiserId; // 测试
  eventForm.value.assetId = queryParams.value.assetId;
  eventForm.value.trackTypes = ['MINI_PROGRAME_API'];
  addCreateEventManagerEvents(eventForm.value)
    .then(() => {
      proxy.$modal.msgSuccess('添加成功');
      dialog.eventVisible = false;
      getList();
    })
    .finally(() => {});
  // }
  // });
};
const getAdvertiserId = async (val) => {
  queryParams.value.advertiserId = val; // 测试才屏蔽
  form.value.advertiserId = val;
  newAdvertiserId.value = val;
  await getList();
};
// 点击小程序
const miniProgramChange = (val) => {
  miniProgramsList.value.forEach((item) => {
    if (item.instanceId == val) {
      form.value.miniProgramAsset.miniProgramName = item.name;
      form.value.miniProgramAsset.miniProgramId = item.appId;
    }
  });
};
// 获取小程序列表
const handleGetMicroWechatAppList = async () => {
  // const res = await getMicroMicroAppList();
  const res = await getQueryToolsMicroAppNew(queryParams.value);
  miniProgramsList.value = res.data;
};
/** 查询商品库列表 */
const getList = async () => {
  loading.value = true;
  const res = await getEventAllAssetsList(queryParams.value);
  productStoreList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  // queryParams.value.advertiserId ="1820572205006868"
  await handleGetMicroWechatAppList();
  if (productStoreList.value.length == 0) {
    return;
  }
  queryParams.value.assetId = res.rows.length > 0 ? res.rows[0]?.assetId : '';
  await handleClick(res.rows[0], 0);
  await handleAvailableEventsList();
  await getEventConfigs(queryParams.value);
};

const getEventConfigs = async (value) => {
  loading.value = true;
  const res = await getEventManagerConfigs(queryParams.value);
  eventConfigsList.value = res.data;
  loading.value = false;
  buttonLoading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialog.eventVisible = false;
  loading.value = false;
  buttonLoading.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  productStoreFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: EventAssetsVo[]) => {
  ids.value = selection.map((item) => item.assetId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleClick = async (row?: EventAssetsVo, index) => {
  queryParams.value.assetId = row?.assetId;
  selectAssetNameId.value = index;
  selectAssetItem.value = row;
  console.log(selectAssetItem.value, 'selectAssetItem.value');
  getEventConfigs(queryParams.value);
  await handleAvailableEventsList();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加资产';
  form.value.assetType = 'MINI_PROGRAME';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: EventAssetsVo) => {
  reset();
  const _platformId = row?.assetId || ids.value[0];
  const res = await getEventAllAssetsList(_platformId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商品库';
};

/** 提交按钮 */
const submitForm = () => {
  form.value.accountId = appStore.accountId;
  form.value.advertiserId = newAdvertiserId.value;
  form.value.miniProgramAsset.miniProgramType = 'APP';
  productStoreFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.log(form.value, 'form.value');

      await addCreateEventManagerAssets(form.value).finally(() => (buttonLoading.value = false));
      // if (form.value.platformId) {
      //   await updateProductStore(form.value).finally(() => (buttonLoading.value = false));
      // } else {
      //   await addProductStore(form.value).finally(() => (buttonLoading.value = false));
      // }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: EventAssetsVo) => {
  const _platformIds = row?.platformId || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品库编号为"' + _platformIds + '"的数据项？').finally(() => (loading.value = false));
  await delProductStore(_platformIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(async () => {
  // await getList();
  // await handleGetMicroWechatAppList();
});
</script>
<style scoped>
.assets-title-text {
  font-size: 12px;
  font-weight: 600;
  color: #999;
  margin: 20px 0;
}
.assets-title-text .text:nth-last-of-type(1) {
  margin-left: 20px;
}
/* 列表容器 */
.vertical-list-container {
  width: 100%;
  height: 65vh;
  /* margin: 20px; */
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  /* overflow: hidden; */
}
.vertical-list-container .list-btn {
  text-align: center;
  margin: 20px 0;
}
/* 列表标题 */
.list-title {
  padding: 16px 20px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

/* 列表项样式 */
.list-item {
  padding: 14px 20px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

/* 列表项悬停效果 */
.list-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

/* 选中状态 */
.list-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  border-left: 3px solid #409eff;
}

/* 最后一项去掉底部边框 */
.list-item:last-child {
  border-bottom: none;
}

/* 图标样式 */
.list-item i {
  margin-right: 8px;
  font-size: 16px;
}
</style>
